#!/usr/bin/Rscript
##########################################################################################
# Issue Ownership and Agenda Setting in the 2019 Swiss National Elections
##########################################################################################
# Description:
# Script for Figure 2
##########################################################################################
# Content
##########################################################################################
# 1) Dependencies
# 2) Startup
# 3) Load Data
# 4) Transform Data
# 5) Figure 2
##########################################################################################
# 1) Dependencies
##########################################################################################
library(dplyr)
library(tidyverse)
library(data.table)
library(readr)
library(lubridate)
library(ggplot2)
library(ggExtra)
library(ggeffects)
library(ggrepel)
library(ggforce)
library(igraph)
library(graphlayouts)
library(ggraph)
library(scales)
library(purrr)
library(magrittr)
library(cowplot)
library(sysfonts)
##########################################################################################
# 2) Startup
##########################################################################################
rm(list=ls())
# - set dir
args = commandArgs()

scriptName = args[substr(args,1,7) == '--file=']

if (length(scriptName) == 0) {
  scriptName <- rstudioapi::getSourceEditorContext()$path
} else {
  scriptName <- substr(scriptName, 8, nchar(scriptName))
}

pathName = substr(
  scriptName, 
  1, 
  nchar(scriptName) - nchar(strsplit(scriptName, '.*[/|\\]')[[1]][2])
)


# - load fonts used in plots
sysfonts::font_add_google("Montserrat", "Montserrat")
sysfonts::font_add_google("Roboto", "Roboto")

# - load ddl theme
suppressMessages(suppressWarnings(source('../ggplot_theme_ddl.R')))
# - pre-setup for figure 1
ddl_theme_2 <- theme(legend.position = "bottom", legend.title = element_blank(), 
                     strip.background = element_blank(), strip.text = element_text(color = "black"),
                     axis.text.x = element_text(angle = 0, hjust = 0.5, vjust = 0.0, size = 16, color = "black"),  
                     axis.text.y = element_text(hjust=0, size = 16, color = "black"),
                     axis.ticks.y = element_blank(),
                     strip.text.x = element_text(size = 16, color = "black"),
                     axis.title = element_text(size = 16, color = "black"),
                     legend.text = element_text(size = 16, color = "black"),
                     plot.title = element_blank(),
                     plot.margin = unit(c(.5,.5,.5,.5), "cm"),
                     legend.key.size = unit(1.5,"line"),
                     legend.key = element_blank(),
                     axis.line.x = element_line(color="black", size = .5),
                     axis.line.y = element_line(color="black", size = .5),
                     panel.spacing.y = unit(2, "lines"),
                     panel.spacing.x = unit(.8, "lines")) 

# - set directory
setwd(pathName)
parent_path <- getwd()
##########################################################################################
# 3) Load Data
##########################################################################################
panelc<- read_csv("../Data/1186_Selects2019_CandidateSurvey_Data_v1.0.0.csv")
##########################################################################################
# 4) Transform Data
##########################################################################################
# Candidates Survey:
issues <- unique(panelc$C1ar)
names(issues) <- c("EU, Europe","Public health","Environment & energy","Social security/welfare state","Economy",
                   "Gender issues & discrimination", "Immigration & asylum", "Political system, parties & politicians",
                   "Regions & national cohesion", "Public services & infrastructure", "Foreign policy & defense",
                   "Labour market", "NA", "Law & order", "Education & culture", "Other problems", "Finances & taxes",
                   "None", "Agriculture")

df <- panelc %>% 
  mutate_at(vars(contains("T9")),
            funs(case_when(.==1~"FDP",
                           .==2~"CVP",
                           .==3~"SP",
                           .==4~"SVP",
                           .==5~"Greens",
                           .==6~"GLP",
                           .==7~"BDP",
                           .==8~"Lega",
                           .==9~"MCG",
                           TRUE~NA_character_))) 

pl <- df %>% dplyr::select(c(T15,T9,C1ar)) %>%
             dplyr::mutate(index = row_number(),
                           dummy = 1) %>% 
             dplyr::mutate_at(vars(contains("C1ar")),
                              funs(case_when(. ==1~"Agriculture",
                                             . ==2~"Economy",
                                             . ==3~"Education & culture",
                                             . ==4~"Environment",
                                             . ==5~"Europe",
                                             . ==6~"Finances & taxes",
                                             . ==7~"Gender",
                                             . ==8~"Immigration",
                                             . ==9~"Foreign policy & defense",
                                             . ==10~"Labour market",
                                             . ==11~"Law & order",
                                             . ==12~"Political system, parties & politicians",
                                             . ==13~"Public health",
                                             . ==14~"Public services & infrastructure",
                                             . ==15~"Regions & national cohesion",
                                             . ==16~"Social security/welfare state",
                                             . ==17~"Other problems",
                                             . ==18~"None",
                                             TRUE~NA_character_))) %>% 
             pivot_wider(names_from = C1ar,
                          values_from = dummy, values_fill = 0)

topic <- c("Environment","Europe","Gender","Immigration")
for(i in 1:4){
  tmp <- pl %>% dplyr::group_by(T9) %>% 
                dplyr::select(c("T15","T9", topic[i]))
  
  colnames(tmp) <- c("T15","T9", "topic")
  
  tmp <- tmp %>% group_by(T9) %>% 
                 dplyr::summarise(frac = mean(topic),
                                  sd = sd(topic),
                                  n = n(),
                                  se = sd / sqrt(n),
                                  qi = se * qt(0.95/2 + .5, n - 1)) %>% 
                 dplyr::mutate(C1ar = topic[i])
  
  if(i == 1){
    pl_fin <- tmp
  } else {
    pl_fin <- dplyr::bind_rows(pl_fin,tmp)
  }
  rm(tmp)
}

pl <- pl_fin %>% dplyr::filter(T9 %in% c("FDP", "CVP", "SP", "SVP", "Greens", "GLP")) %>% 
                 dplyr::ungroup() %>% 
                 dplyr::arrange(C1ar, frac) %>% 
                 dplyr::mutate(order = row_number()) %>% 
                 dplyr::mutate(C1ar = fct_relevel(C1ar, "Environment", "Gender", "Europe", "Immigration")) 
##########################################################################################
# 5) Figure 2
##########################################################################################
ggplot(data = pl, aes(y = frac, x = order, fill = C1ar)) +
  geom_col(position = position_dodge(width = 0.8), width = .9, alpha = 0.75) +
  facet_wrap(~C1ar, scales = "free_y", ncol = 2) +
  scale_x_continuous(breaks = pl$order,
                     labels = pl$T9,
                     expand = c(0,0)) +
  scale_y_continuous(labels = scales::percent) +
  scale_color_manual(labels = c("Environment","Gender","Europe","Immigration"), values = c("#009E73","#DD2461","#0072B2","#999999")) +
  scale_fill_manual(labels = c("Environment","Gender","Europe","Immigration"), values = c("#009E73","#DD2461","#0072B2","#999999")) +
  labs(x = "Party", y = "Share of candidates", title = "") +
  coord_flip() +
  ddl_theme_2 +
  theme(legend.position = "none", legend.title = element_text(size = 16, color = "black"), 
        strip.background = element_blank(), strip.text = element_text(color = "black"),
        strip.text.x = element_text(size = 19, color = "black"),
        axis.title = element_text(size = 19, color = "black"),
        plot.title = element_blank(),
        legend.text = element_text(size = 16, color = "black"),
        legend.key = element_blank(),
        plot.margin = unit(c(.5,1.3,.5,.5), "cm"),
        legend.key.size = unit(1.5,"line"),
        axis.line.x = element_line(color="black", size = .5),
        axis.line.y = element_line(color="black", size = .5),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank(),
        axis.text.x = element_text(angle = 0, hjust = 0.5, vjust = 0.0, size = 16, color = "black"),  
        axis.text.y = element_text(hjust=0, size = 16, color = "black"))
ggsave(filename = paste0("../images/figure_2.pdf"),  width = 24, height = 16, device = cairo_pdf, units = "cm")
##########################################################################################